from django.shortcuts import render
from myapp.models import LoginModel, Get_BookModel, WaitBookModel, IwantLookModel
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.jwttool import tooljwt
from utils.sendmsg import send_message
from django.db.models import Q
from rest_framework.generics import ListAPIView
from myapp.serializer import LoginSerializer,WaitBookSerializer,IwantLookSerializer,GetBookSerializer
import random


# Create your views here.
class LoginView(APIView):
    def post(self, request):
        phone = request.data.get("phone")
        password = request.data.get("password")
        info = LoginModel.objects.filter(phone=phone).first()
        if info is None:
            return Response({"code": 400, "msg": "账号不存在"})
        elif info.password == password:
            data = {
                "id": info.id,
                "phone": phone,
                "token": tooljwt.getToken(info.id, phone)
            }
            return Response({"code": 200, "msg": "登录成功", "data": data})
        return Response({"code": 400, "msg": "登录失败"})


class Loginpwd(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        info = LoginModel.objects.filter(phone=phone).first()
        if info is None:
            return Response({"code": 400, "msg": "账号不存在"})
        data = {
            'id': info.id,
            'phone': phone,
            'token': tooljwt.getToken(info.id, phone)
        }
        return Response({"code": 200, "msg": "登录成功", "data": data})


# class SendCodeView(APIView):
#     def get(self,request):
#         send_message('15663393196',str(random.randint(1000,9999)))
#         return Response({"code":200,"msg":"发送成功"})
class WaitBookView(ListAPIView):
    queryset = WaitBookModel.objects.all()
    serializer_class = WaitBookSerializer


class WantLookView(ListAPIView):
    queryset = IwantLookModel.objects.all()
    serializer_class = IwantLookSerializer

    def get_queryset(self):
        book_cate = self.request.query_params.get('book_cate')
        name = self.request.query_params.get('name')
        author = self.request.query_params.get('author')
        HouseModel = self.request.query_params.get('HouseModel')
        query = Q()
        if book_cate:
            query = Q(book_cate=book_cate)
        if name:
            query = query & Q(name__contains=name)
        if author:
            query = query & Q(author__contains=author)
        if HouseModel:
            query=query & Q(HouseModel=HouseModel)
        return IwantLookModel.objects.filter(query)
class GetBookView(ListAPIView):
    queryset = Get_BookModel.objects.all()
    serializer_class = GetBookSerializer

